﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using FileSystemCustomClasses;

namespace FileTrackerWPF
{
	public interface IConfigurationHandler
	{
		List<IoFavorite> FavoriteList { get; }
		String LeftDefaultDir { get; }
		String RightDefaultDir { get; }
		void Save();
	}

	public class ConfigurationHandler : IConfigurationHandler
	{
		public List<IoFavorite> FavoriteList
		{
			get
			{
				if (_configuration == null)
				{
					Reload();
				}

				return _configuration.Favorites;
			}
		}

		public String LeftDefaultDir
		{
			get
			{
				if(_configuration == null)
				{ Reload();}

				return _configuration.LeftDefaultDir;
			}
		}

		public String RightDefaultDir
		{
			get
			{
				if(_configuration == null)
				{ Reload();}
				return _configuration.RightDefaultDir;
			}
		}

		private object _fileLock;
		private FileTrackerConfiguration _configuration;
		private readonly string _path;
		private string _leftDefaultDir;
		private string _rightDefaultDir;

		public ConfigurationHandler(string argAppPath)
		{
			_fileLock = new object();
			DirectoryInfo configPath = new DirectoryInfo(argAppPath);
			_path = configPath.FullName + @"\FileTrackerConfig.config";
		}

		public void Save()
		{
			//Lock it so I don't step on a Reload
			lock(_fileLock)
			{
				if (_configuration == null)
				{
					_configuration = new FileTrackerConfiguration();
				}

				using (Stream serializationStream = File.Open(_path, FileMode.Create))
				{
					BinaryFormatter binFormatter = new BinaryFormatter();

					binFormatter.Serialize(serializationStream, _configuration);
				}
			}
		}

		private void Reload()
		{
			//lock it incase it's called by more than one thread
			lock(_fileLock)
			{
				//Check if the _configuration was created while I was waiting.
				if(_configuration != null)
				{ return;}

				_configuration = null;

				FileInfo testFile = new FileInfo(_path);

				if ((testFile.Exists) && (testFile.Length > 0))
				{

					BinaryFormatter binFormatter = new BinaryFormatter();

					try
					{
						using (Stream serializationStream = File.Open(_path, FileMode.Open))
						{
							_configuration = binFormatter.Deserialize(serializationStream) as FileTrackerConfiguration;
						}
					}
					catch (SerializationException)
					{
						//If there's a problem with serialization then just make a new Config object.
						_configuration = new FileTrackerConfiguration();
					}
				}

				if (_configuration == null)
				{
					_configuration = new FileTrackerConfiguration();
				}
			}

		}
		
	}
}
